﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Drawing;
using System.Drawing.Imaging;
using System.IO;
using System.Drawing.Drawing2D;

namespace d39
{
    public partial class PlayerImage : System.Web.UI.Page
    {
        protected void Page_Init(object sender, EventArgs e)
        {
            Response.ContentType = "image/png";
            Response.SetCachingHeaders();
            var player = Player.FromString(Request.QueryString["p"], DnDVersion.V35);
            var grid = new Grid()
            {
                PixelSize = int.Parse(Request.QueryString["px"] ?? "10"),
                Width = player.SizeInSquares,
                Height = player.SizeInSquares,
                Players = { player },
            };

            using (var image = new Bitmap(grid.GetImageWidth(UrlTweaks.Default), grid.GetImageHeight(UrlTweaks.Default), PixelFormat.Format32bppArgb))
            {
                using (var graphics = Graphics.FromImage(image))
                {
                    graphics.SmoothingMode = SmoothingMode.HighQuality;
                    player.Draw(graphics, grid, new Coordinate(1, 1), !player.IsAllInvisible, player.IsAllInactive, Moves.None);
                }
                using (var memory = new MemoryStream())
                {
                    image.Save(memory, ImageFormat.Png);
                    Response.BinaryWrite(memory.ToArray());
                    Response.Flush();
                    Response.End();
                }
            }
        }
    }
}